package org.ichihamigua.gateway.filter;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.DownloadUrl;
import com.qiniu.util.Auth;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Component
public class CdnRedirectFilter implements GlobalFilter, Ordered {

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println(exchange.getRequest().getPath());
        String path = exchange.getRequest().getPath().value();
        if(path.startsWith("/src")){
            try {
                String url = new DownloadUrl(
                        "s33ii76i8.hn-bkt.clouddn.com",
                        false,
                        path.substring(5)
                ).buildURL(
                        Auth.create(
                                "bHtuDg-rbvemwPhvsrioVM6uc5hL8-06BP3tD3Yn",
                                "UwMc9KfOqA8ZyrEdNFr1i4UYNV2HIrhSrsK2ipsP"
                        ),
                        LocalDateTime.now().plusHours(24).toEpochSecond(ZoneOffset.UTC)
                );
                System.out.println("重定向"+ url);
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set("Location", url);
                return exchange.getResponse().setComplete();
            } catch (QiniuException e) {
                throw new RuntimeException(e);
            }
        }

        return chain.filter(exchange);
    }

    /**
     * 指定过滤器的执行顺序 , 返回值越小,执行优先级越高
     */
    public int getOrder() {
        return 0;
    }
}

